package com.test.cordova.util;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * MD5加密
 */
public class MD5Util {

    /**
     * 生成秘钥
     * @param username  用户名
     * @param secret 秘钥串  例如：6AD569ADAD218F8467EF864782215D2C
     * @param timestamp 当前时间戳
     * @return
     */
    public static String generatedCiphertext(String username, String secret, String timestamp) {
        String[] strs = new String[]{timestamp, secret, username};
        Arrays.sort(strs);
        return getMD5(getMD5(strs[0] + strs[1] + strs[2] + secret) + secret);
    }

    /**
     * MD5加密
     * @param message 要进行MD5加密的字符串
     * @return 加密结果为32位字符串
     */
    public static String getMD5(String message) {
        MessageDigest messageDigest = null;
        StringBuffer md5StrBuff = new StringBuffer();
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(message.getBytes("UTF-8"));

            byte[] byteArray = messageDigest.digest();
            for (int i = 0; i < byteArray.length; i ++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                }else {
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return md5StrBuff.toString().toUpperCase();//字母大写
    }




}
